package com.yichen.rent.service;

import com.yichen.rent.dao.MessageDao;

import com.yichen.rent.pojo.Message;

import com.yichen.rent.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.*;

@Service
public class MessageService {


    @Autowired
    private MessageDao messageDao;

    @Autowired
    private IdWorker idWorker;


    public List<Message> queryMessageList(String  fromId, String toId) {
        List<Message> list = messageDao.findListByFromAndTo(fromId, toId);
        for (Message message : list) {
            //如过消息为未读
            if(message.getStatus() == 1){
                // 修改消息状态为已读
                updateMessageState(message.getId(),2);
            }
        }
        return list;
    }


   /* public List<Message> findListByFromAndTo(String fromId, String toId) {
        return messageDao.findListByFromAndTo(fromId,toId);
    }*/

    public Message findMessageById(String id) {
        Optional<Message> op = messageDao.findById(id);
        return op.orElse(null);
    }

    public void updateMessageState(String id, Integer status) {
        Optional<Message> optionalMessage = messageDao.findById(id);
        if (optionalMessage.isPresent()) {
            Message message = optionalMessage.get();
            message.setStatus(status);
            messageDao.save(message);
        }
    }

    public void saveMessage(Message message) {
        message.setId(idWorker.nextId()+"");
        message.setSendDate(DateUtil.dateToString(new Date(),"yyyy-MM-dd"));
        message.setStatus(1);
        messageDao.save(message);
    }

    public void deleteMessage(String id) {
        messageDao.deleteById(id);
    }
}